let cloud = wx.cloud
wx.cloud.init()
// 还原上个页面的参数到 options, 并删除 options.params  
const extractParams = function (query = {}) {  
    const { params } = query  
    let options = { ...query }  
  
    if (params !== undefined) {  
      options = {  
        ...options,  
        ...JSON.parse(decodeURIComponent(params)),  
      }  
      delete options.params  
    }  
  
    return options  
  }  
  
  const originPage = Page  
  
  // 对微信原来的 Page 函数进行扩展  
  Page = function (config = {}) {  
    // 重写 Page 的 onLoad 函数, 还原上个页面传进来的参数  
    let { onLoad } = config  
    config.onLoad = function (options = {}) {  
        let tuijianPath = getCurrentPages().reverse()[0].route
        let tuijianQuery = Object.keys(options).map(item=>{
            return item+'='+options[item]
        }).join('&')
        let tuisongPathList = wx.getStorageSync('tuisongPathList')||[]
        tuisongPathList.push({
            "path": tuijianPath,
            "query": tuijianQuery
        })
        wx.setStorageSync('tuisongPathList', tuisongPathList)
        onLoad && onLoad.call(this, extractParams(options))  
    }  
  
    return originPage(config)  
  } 
App({
    getRandomAd(isOnLoad,e){
        let that = e||this
        that.getRandomAd = function(a,b){
            if(a !== undefined){
                if(b !== undefined){
                    that.setData({
                        ad: getApp().globalData.selfAd.filter(item=>item.type == 'video')[parseInt(getApp().globalData.selfAd.filter(item=>item.type == 'video').length*Math.random())]
                    });
                } else {
                    that.setData({
                        ad: getApp().globalData.selfAd[parseInt(getApp().globalData.selfAd.length*Math.random())]
                    });
                }
            }
        }
    },
    chaping(isShow){
        // return
        if(!isShow){
            return
        }
        let that = this
        that.globalData.interstitialAd = null
            if (wx.createInterstitialAd) {
                that.globalData.interstitialAd = wx.createInterstitialAd({
                adUnitId: that.globalData.adTest.filter(item=>{
                    return item.type == 'chaping'
                })[0].id
                })
                // let show = 1
                // wx.showLoading({
                //   title: '请稍等...',
                //   mask:true
                // })
                that.globalData.interstitialAd.onLoad(() => {
                    // if(show == 2){
                    //     return
                    // }
                    // show = 2
                    if (that.globalData.interstitialAd) {
                        
                        that.globalData.interstitialAd.show()
                        .then(()=>{
                            wx.hideLoading({
                              success: (res) => {},
                            })
                            console.log('show')
                            wx.setStorageSync('chapingShow', true)
                        })
                        .catch((err) => {
                            wx.hideLoading({
                                success: (res) => {},
                              })
                            console.error(err,'插屏广告show错误')
                        })
                    }
                })
                that.globalData.interstitialAd.onError((err) => {
                    console.log(err,'拉取广告错误')
                    wx.hideLoading({
                        success: (res) => {},
                      })
                })
                that.globalData.interstitialAd.onClose(() => {})
            }
        
    },
    // chaping(isShow){
    //     // return
    //     console.log(wx.getStorageSync('jiange'))
    //     if(wx.getStorageSync('chapingShow')){
    //         return
    //     }
    //     if(!wx.getStorageSync('jiange')){
    //         return
    //     }
    //     console.log(new Date().getTime() - wx.getStorageSync('jiange'))
    //     if(new Date().getTime() - wx.getStorageSync('jiange')<20000){
    //         return
    //     }
    //     wx.setStorageSync('jiange', new Date().getTime())
    //     console.log('aaaaaaa')
    //     let that = this
    //     that.globalData.interstitialAd = null
    //         if (wx.createInterstitialAd) {
    //             that.globalData.interstitialAd = wx.createInterstitialAd({
    //             adUnitId: that.globalData.adTest.filter(item=>{
    //                 return item.type == 'chaping'
    //             })[0].id
    //             })
    //             let show = 1
    //             // wx.showLoading({
    //             //   title: '请稍等...',
    //             //   mask:true
    //             // })
    //             that.globalData.interstitialAd.onLoad(() => {
    //                 if(show == 2){
    //                     return
    //                 }
    //                 show = 2
    //                 if (that.globalData.interstitialAd) {
                        
    //                     that.globalData.interstitialAd.show()
    //                     .then(()=>{
    //                         wx.hideLoading({
    //                           success: (res) => {},
    //                         })
    //                         console.log('show')
    //                         wx.setStorageSync('chapingShow', true)
    //                     })
    //                     .catch((err) => {
    //                         wx.hideLoading({
    //                             success: (res) => {},
    //                           })
    //                         console.error(err,'插屏广告show错误')
    //                     })
    //                 }
    //             })
    //             that.globalData.interstitialAd.onError((err) => {
    //                 console.log(err,'拉取广告错误')
    //                 wx.hideLoading({
    //                     success: (res) => {},
    //                   })
    //             })
    //             that.globalData.interstitialAd.onClose(() => {})
    //         }
        
    // },
    checkMsg(e){
        console.log(e)
        wx.showLoading({
          title: '请稍等...',
        })
        return new Promise((resolve,reject)=>{
            // cloud.callFunction({
            //     name:'checkMsg',
            //     data: {data:e},
            //     success(res){
            //         resolve(res)
            //         wx.hideLoading()
            //     },
            //     fail(res){
            //         console.log(res)
            //         resolve(undefined)
            //         wx.hideLoading()
            //     }
            // })
            wx.request({
                url: this.globalData.requestUrl+"/xiaochengxu/msgCheck",
                method:'POST',
                data:{
                    msg:e
                },
                success(res){
                    console.log(res,'文字验证')
                    res.data.errCode = res.data.errcode
                    res.result = res.data
                  resolve(res)
                  wx.hideLoading()
                },
              fail(res){
                  console.log(res)
                  resolve(undefined)
                  wx.hideLoading()
              }
              })
        })
    },
    checkImg(e,outThat){
        console.log(e)
        let that = this
        wx.showLoading({
          title: '验证中...',
        })
        return new Promise((resolve,reject)=>{
            wx.getImageInfo({
                src: e,  
                success: function(res){
                    //---------利用canvas压缩图片--------------
                    var ratio = 2;
                    var canvasWidth = res.width //图片原始长宽
                    var canvasHeight = res.height
                    while (canvasWidth > 400 || canvasHeight > 400){// 保证宽高在400以内
                        canvasWidth = Math.trunc(res.width / ratio)
                        canvasHeight = Math.trunc(res.height / ratio)
                        ratio++;
                    }
                    outThat.setData({
                        cWidth: canvasWidth,
                        cHeight: canvasHeight
                    })
                
                    //----------绘制图形并取出图片路径--------------
                    var ctx = wx.createCanvasContext('canvasOut',outThat)
                    ctx.clearRect(0, 0, canvasWidth, canvasHeight)
                    ctx.drawImage(res.path, 0, 0, canvasWidth, canvasHeight)
                    ctx.draw(false, setTimeout(function(){
                        wx.canvasToTempFilePath({
                            canvasId: 'canvasOut',
                            destWidth: canvasWidth,
                            destHeight: canvasHeight,
                            success: function (res) {
                                console.log(res.tempFilePath,'最终图片路径')//最终图片路径
                                if(that.globalData.isCheck){
                                    // wx.getFileSystemManager().readFile({
                                    //     filePath:res.tempFilePath,
                                    //     encoding:'base64',
                                    //     success(res){
                                    //         cloud.callFunction({
                                    //             name:'checkImg',
                                    //             data: {data:res.data},
                                    //             success(res){
                                    //                 resolve(res)
                                    //                 wx.hideLoading()
                                    //             },
                                    //             fail(res){
                                    //                 console.log(res)
                                    //                 resolve(undefined)
                                    //                 wx.hideLoading()
                                    //             }
                                    //         })
                                    //     },
                                    //     fail(res){
                                    //         resolve(undefined)
                                    //         wx.hideLoading()
                                    //     }
                                    // })
                                
                                    wx.uploadFile({
                                        url: that.globalData.requestUrl+"/xiaochengxu/imgCheck",
                                        filePath: res.tempFilePath,
                                        name: "file",
                                        formData: {
                                            order: new Date().getTime() * 1e6 + parseInt(Math.random() * 1e6),
                                            now: 0
                                        },
                                        success: function success(res) {
                                            console.log(res, '图片验证');
                                            wx.hideLoading()
                                            if (res.data.indexOf("<") != -1) {
                                                resolve(undefined)
                                                that.tip("上传失败，请重试");
                                                return;
                                            }
                                            res.data = JSON.parse(res.data);
                                            if (res.data == "fail") {
                                                resolve(undefined)
                                                that.tip("图片异常");
                                            }
                                            if (res.data.errcode == 0) {
                                                resolve({result:{errCode:0}})
                                            } else if (res.data.errcode == 87014) {
                                                resolve(undefined)
                                                that.tip("图片违规");
                                            } else {
                                                resolve(undefined)
                                                that.tip(res.data.data || "上传失败");
                                            }
                                        },
                                        fail: function fail(res) {
                                            that.tip("上传失败，请重试");
                                        }
                                    });
                                } else {
                                    resolve({result:{errCode:0}})
                                    wx.hideLoading()
                                }
                            },
                            fail: function (res) {
                                resolve(undefined)
                                wx.hideLoading()
                            }
                        },outThat)
                    },100))    //留一定的时间绘制canvas
                },
                fail: function(res){
                    resolve(undefined)
                    wx.hideLoading()
                },
             })
        })
       
    },
    tip: function tip(text, time) {
        wx.showToast({
            title: text,
            icon: "none",
            duration: time || 1500,
            mask: false
        });
    },
    getUser(callback){
        cloud.database().collection('user').where({
            openId: wx.getStorageSync('openId') // 填入当前用户 openid
        })
        .get()
        .then((e)=>{
            console.log(e)
            if(e.data.length != 0){
              let date = new Date()
              wx.setStorageSync('userInfo', e.data[0].userInfo)
              if (e.data[0].userInfo.date != (date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate())){
                
                cloud.database().collection('user')
                  .where({
                    openId: wx.getStorageSync('openId')
                  })
                  .update({
                    // data 传入需要局部更新的数据
                    data: {
                      userInfo:{
                        date: date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate(),
                        count:15,
                        zhuli:5
                      }
                    }
                  })
                  .then((res)=>{
                    wx.setStorageSync('loginTime', date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate())
                    e.data[0].userInfo.date = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate()
                    e.data[0].userInfo.count = 15
                    e.data[0].userInfo.zhuli = 5
                    wx.setStorageSync('userInfo', e.data[0].userInfo)
                    callback()
                  })
              }
            }
            callback()
        })
        .catch((e)=>{
            wx.hideLoading()
        })
    },
    WX_LOGIN(callback){
        let that = this
        let date = new Date()
      if (wx.getStorageSync('loginTime') == (date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate())&&wx.getStorageSync('userInfo')){
            callback()
            return
        }
        wx.showLoading({
          title: '请稍等...',
        })
        if(wx.getStorageSync('openId')){
            this.getUser(callback)
            return
        } else{
            cloud.callFunction({
                name:'openapi',
                success(res){
                    console.log(res)
                    wx.setStorageSync('openId', res.result.event.userInfo.openId)
                    that.getUser(callback)
                },
                fail(res){
                    console.log(res)
                    wx.hideLoading()
                }
            })
        }
        
    },
    onHide(){
        let tuisongPathList = wx.getStorageSync('tuisongPathList')||[]
        if(tuisongPathList.length){
            wx.setStorageSync('tuisongPathList', [])
            wx.cloud.callFunction({ //获取openid------------
                name: 'tuisong',
                data:{
                    pathList:tuisongPathList
                }
            }).then(res => {
             console.log("res", res)
            }).catch(err => {
             console.log(err)
            })
        }
    },
    onLaunch: function() {
        console.log(new Date().getTime()+24*60*60*1000)
        wx.setStorageSync('jiange', new Date().getTime())
        if(!wx.getStorageSync('lastTime')){
            wx.setStorageSync('lastTime', new Date().getFullYear()+'='+(new Date().getMonth()+1)+'-'+new Date().getDate())
            wx.setStorageSync('chapingShow', false)
        } else {
            if(wx.getStorageSync('lastTime') == new Date().getFullYear()+'='+(new Date().getMonth()+1)+'-'+new Date().getDate()){

            } else {
                wx.setStorageSync('chapingShow', false)
            }
        }
        var t = this;
        let that = this
        
        var e = wx.getStorageSync("logs") || [];
        e.unshift(Date.now()), wx.setStorageSync("logs", e);
        var s = this;
        this.globalData.myDevice = wx.getSystemInfoSync();
        for (var a = 0; a < 156; a++) this.globalData.imgUrl[a] = "https://ishare20.net/emotion/" + (a + 1) + ".png";
        wx.login({
            success: function(t) {}
        }), wx.getSetting({
            success: function(e) {
                e.authSetting["scope.userInfo"] && wx.getUserInfo({
                    success: function(e) {
                        t.globalData.userInfo = e.userInfo, t.userInfoReadyCallback && t.userInfoReadyCallback(e);
                    }
                });
            }
        }), wx.request({
            url: "https://ishare20.net/gifmaker/appset.json",
            headers: {
                "Content-Type": "application/json"
            },
            success: function(t) {
                s.globalData.appset = t.data;
            }
        }), wx.request({
            url: "https://ishare20.net/gifmaker/wxminiset.json",
            headers: {
                "Content-Type": "application/json"
            },
            success: function(t) {
                s.globalData.wxminiset = t.data;
            }
        });
    },
    globalData: {
        userInfo: null,
        myDevice: null,
        imgUrl: [],
        ad: {},
        apiUrl: "https://ishare20.net/textToPic",
        appset: {},
        appid: "wxb8dcb03dab37e2f8",
        wxminiset: [],
        tuijian:[],
        // p图拼图修图神器 appid:wx7b161ed24af0841b
        // p图图片拼图神器 appid:wxe021ee9d2c2db39a
        // p图修图图片工具 appid:wx31d2865b03a4ff17
        // p图图片修图神器 appid:wx74d2a9990909745d
        // p图修图神器 appid:wxcf7ddededa200983
        // 抠图拼图合成神器 appid:wxf735b8614b3ee83e
        // 拼图抠图合成神器 appid:wx76cc9c12e43a20f8
        // p图批图神器 appid:wx4a6c62073a040163
        // 修图p图神器 appid:wx83ad4292da61861a
        selfAd:[{id:'adunit-8dea2c24d93867d7',type:'video'}],
      adTest:[{id:'adunit-319b468c37dafdb0',type:'chaping'}],
      jili:'adunit-6b6a93f2f288ab1d',
        // 做图p图工具 appId:wxab27a928081526f6	
    //   selfAd:[{id:'adunit-9afb585d5f04402d',type:'video'}],
    //   adTest:[{id:'adunit-dc4fe69fb68f9a4d',type:'chaping'}],
    //   jili:'adunit-fb737ea7dd4bd327',
        // 批图修图工具 appid:wx010fef090413d436
    //   selfAd:[{id:'adunit-1b3f9c1b1fa34378',type:'video'}],
    //   adTest:[{id:'adunit-53499f50c09920a7',type:'chaping'}],
    //   jili:'adunit-a57669fc5aa3428b',
      // 批图工具 appid:wx71bf0f1f5f1cb058
    //   selfAd:[{id:'adunit-55cf524503c3d618',type:'video'}],
    //   adTest:[{id:'adunit-cdc37b71cfcf2aaa',type:'chaping'}],
    //   jili:'adunit-64effbc11f85d248',
    //   p图修图工具 appid:wx521e3f82f19f8803
    //   selfAd: [{id:'adunit-f50569eb1835a037',type:'video'}],
    //   adTest: [{id:'adunit-b640b93445988647',type:'chaping'}],
    //   jili:'adunit-97d0452ec5f80d1e',
    // 抠图p图工具 appId:wx5ac4fe671847cf04
    //   selfAd: [{id:'adunit-28da339203c3c3a7',type:'video'}],
    //   adTest: [{id:'adunit-b311f418fc8cddda',type:'chaping'}],
    //   jili:'adunit-6453114fcf4c98eb',
     // 修图p图工具 appid:wx80cc7223690f301b
    //   selfAd: [{id:'adunit-925bfca5fbffdcee',type:'video'}],
    //   adTest: [{id:'adunit-8f5590e871cd587d',type:'chaping'}],
    //   jili:'adunit-82fa443c031ef390',
      interstitialAd:null,
        test:0,
        onload:true,
        chaping:true,
        bgThemeColor:'#009688',
        isCheck:true,
        requestUrl:'https://guanhe.work',
        tuijiantype:''
    }
});